package com.liuya.interceptor;

import com.liuya.common.Constants;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 刘亚
 * @Date 2016/12/26
 */
public class UserInterceptorHandler extends HandlerInterceptorAdapter {
    private String exclude  ;
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView view) throws Exception {
        if(view!=null){
            view.addObject("user", SecurityUtils.getSubject().getSession().getAttribute(Constants.USER_SESSION_NAME)) ;
            HandlerMethod handlerMethod = (HandlerMethod ) arg2 ;
            RequestMapping obj = handlerMethod.getMethod().getAnnotation(RequestMapping.class) ;
//            view.addObject("subtype", obj.subtype()) ;
//            view.addObject("mantype", obj.type()) ;
        }
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        boolean filter = false;
        for (String s : exclude.split(",")) {
            if (uri.matches(s)) {
                filter = true;
                break;
            }
        }
        if(!filter){
            filter = SecurityUtils.getSubject().getSession().getAttribute(Constants.USER_SESSION_NAME)!=null ;
        }
        if(!filter && uri.indexOf("/",1)>=0){
            response.sendRedirect("/");
            /**
             * 记录Refer信息
             */
            if(uri.indexOf("logout") < 0){
                if(request.getSession().getAttribute(Constants.REFER_STR)!=null){
                    request.getSession().removeAttribute(Constants.REFER_STR);
                }
                request.getSession().setAttribute(Constants.REFER_STR, uri);
            }
        }
        return filter ;
    }
    public String getExclude() {
        return exclude;
    }
    public void setExclude(String exclude) {
        this.exclude = exclude;
    }
}
